var express = require('express');
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res, next) {
  var usersCollection = res.db.get("users");
  usersCollection.find({}, {}, function(e, docs) {
  	// console.log(docs);
  	res.render('index', { title: 'Express ToDo',
  		subject: 'NodeJs + Express + Jade + MongoDb',
  		users: docs
  	 });
  });
  
});

router.get('/addnew', function(req, res, next) {
	res.render('addnew')
});

router.get('/remove', function(req, res, next){
	var username = req.query.username;
	var db = res.db;
	db.get('users').remove({ username: username}, function(err, docs) {
		if(!err) {
			res.redirect('/');
		}else{
			res.send('remove error');
		}
	})
});

router.post('/addnew', function(req, res, next){
	var db = res.db;
	var username = req.body.username;
	var json = { username: username };
	var usersCollection = db.get('users');
	usersCollection.insert(json, function(err, doc) {
		if(!err) {
			res.redirect('/');
		}else{
			res.send('addnew error');
		}
	});
});



module.exports = router;
